<?php

    require_once( "includes/config.inc.php" );
	
    class DataBase
    {
        private $dbLink;
		private $template;
        
        private function __construct()
        {
            $this->dbLink = NULL;
			$this->template = new TemplateEngine();
        }
		
		private function connect( $host, $user, $password, $dbName )
		{
			$this->dbLink = mysqli_connect( $host, $user, $password, $dbName, '3306');
			$error = mysqli_connect_error();
			if ( $error )
			{
				throw new Exception( $this->template->convertToHtml( "Unable to connect to database!" ) );
			}
		}
		
		public static function getInstance()
		{
			static $db = NULL;
			if ( !$db )
			{
				$db = new DataBase();
				$db->connect( DB_HOST, DB_USER, DB_PASSWORD, DB_NAME );
			}
			return $db;
		}
		
		public function quote( $str )
		{
			return ( mysqli_real_escape_string( $this->dbLink, $str ) );
		}
		
		public function query( $query )
		{
			$resultSet = mysqli_query( $this->dbLink, $query );
			if ( gettype( $resultSet ) != "boolean" )
			{
				$i = 0;
				$arrSet = array(); 
				while ( $row = mysqli_fetch_assoc( $resultSet ) )
				{
					$arrSet[$i] = $row;
					$i++;
				}
				mysqli_free_result( $resultSet ); 
				return $arrSet;
			}
		}

		public function getLastId()
		{
			return mysqli_insert_id( $this->dbLink );
		}
	}

?>
